from flask import Flask
from flask_migrate import Migrate
from flask_script import Manager
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from app.house_views import house_bp
from app.main import main_bp
from app.models import db, User, House, Order, HouseImage, Facility, Area, OrderContract
from app.order_views import order_bp
from app.user_views import user_bp, login_manager

app = Flask(__name__)

# 注册蓝图
app.register_blueprint(blueprint=main_bp, url_prefix='/')
app.register_blueprint(blueprint=house_bp, url_prefix='/house')
app.register_blueprint(blueprint=order_bp, url_prefix='/order')
app.register_blueprint(blueprint=user_bp, url_prefix='/user')

# 设置密钥
app.secret_key = '12345678sdfghjkxcvbnm'

# 初始化数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:cMS050306@127.0.0.1:3306/lovehouse'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

login_manager.init_app(app)

# 添加迁移脚本命令到manager中
manage = Manager(app)

# 使用migrate绑定app和db
migrate = Migrate(app, db)

# 初始化 Flask-Admin
admin = Admin(app, name='爱之家管理系统', template_mode='bootstrap3')


# 自定义 User 模型视图
class UserAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'phone', 'name', 'avatar', 'id_name', 'id_card', 'houses', 'orders']
    column_labels = {
        'id': '编号',
        'phone': '手机号',
        'pwd_hash': '密码哈希',
        'name': '用户名',
        'avatar': '头像',
        'id_name': '实名认证姓名',
        'id_card': '身份证号码',
        'houses': '房屋信息',
        'orders': '订单信息',
    }
    form_columns = ['phone', 'name', 'avatar', 'id_name', 'id_card']


class HouseAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'title', 'price', 'address', 'room_count', 'acreage', 'unit', 'capacity', 'beds', 'deposit',
                   'min_days', 'max_days', 'order_count', 'index_image_url']

    column_labels = {
        'id': '房屋编号',
        'title': '标题',
        'price': '单价(分)',
        'address': '地址',
        'room_count': '房间数',
        'acreage': '房屋面积',
        'unit': '房屋单元',
        'capacity': '容纳人数',
        'beds': '床铺配置',
        'deposit': '房屋押金',
        'min_days': '最少入住天数',
        'max_days': '最多入住天数',
        'order_count': '订单数',
        'index_image_url': '房屋主图片',
    }

    form_columns = ['user_id', 'area_id', 'title', 'price', 'address', 'room_count', 'acreage', 'unit', 'capacity',
                    'beds', 'deposit', 'min_days', 'max_days', 'order_count', 'index_image_url']


# 自定义 HouseImage 模型视图
class HouseImageAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'house_id', 'url']
    column_labels = {
        'id': '编号',
        'house_id': '房屋编号',
        'url': '图片地址',
    }
    form_columns = ['house_id', 'url']


# 自定义 Facility 模型视图
class FacilityAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'name', 'css']
    column_labels = {
        'id': '编号',
        'name': '设施名称',
        'css': 'CSS 样式',
    }
    form_columns = ['name', 'css']


class AreaAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'name']  # 列出需要展示的字段
    column_labels = {
        'id': '区域编号',
        'name': '区域名称'
    }
    form_columns = ['name']  # 设置表单展示的字段


class OrderAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'user_id', 'house_id', 'begin_date', 'end_date', 'amount', 'status', 'comment']
    column_labels = {
        'id': '订单编号',
        'user_id': '用户编号',
        'house_id': '房屋编号',
        'begin_date': '入住日期',
        'end_date': '离店日期',
        'amount': '总金额',
        'status': '订单状态',
        'comment': '评论'
    }
    form_columns = ['user_id', 'house_id', 'begin_date', 'end_date', 'amount', 'status', 'comment']


class OrderContractAdmin(ModelView):
    column_display_pk = True
    column_list = ['id', 'order_id', 'contract_path', 'order']
    column_labels = {
        'id': '订单编号',
        'order_id': '订单编号',
        'contract_path': '保存路径',
        'order': '订单'
    }
    form_columns = ['id', 'order_id', 'contract_path', 'order']


# 添加模型到 Flask-Admin 中
admin.add_view(UserAdmin(User, db.session, name='用户'))
admin.add_view(HouseAdmin(House, db.session, name='房屋'))
admin.add_view(OrderAdmin(Order, db.session, name='订单'))
admin.add_view(HouseImageAdmin(HouseImage, db.session, name='房屋图片'))
admin.add_view(FacilityAdmin(Facility, db.session, name='设施'))
admin.add_view(AreaAdmin(Area, db.session, name='区域'))
admin.add_view(OrderContractAdmin(OrderContract, db.session, name='合同'))


# 创建一个默认管理员账号
@app.before_first_request
def create_admin():
    with app.app_context():
        admin_user = User.query.filter_by(name='admin').first()
        if not admin_user:
            admin_user = User(
                phone='12345678901',  # 您可以随意设定管理员的手机号
                name='admin',
                password='admin',  # 使用setter方法设置密码，会自动生成哈希
            )
            db.session.add(admin_user)
            db.session.commit()
            print("Default admin account created: Username=admin, Password=admin")


if __name__ == '__main__':
    manage.run()
